<?php
/**
 * Kbs
 *
 * To provide the components
 */
require_once('Kbs/Interface.php');

Abstract class Kbs
{
    const DEVELOPMENT   = 'development';
    const TESTING       = 'testing';
    const PRODUCTION    = 'production';
    static $PE = '';

    const ERROR_DEVELOPMENT = 520;

    /**
     * Project environment
     *
     */
    public static function setProjectEnvironment()
    {
        if (empty(self::$PE)) {
            $env = getenv('SECTION_CONFIG');

            switch ($env) {
                case self::DEVELOPMENT:
                    ini_set('error_reporting', E_ALL | E_STRICT);
                    ini_set('display_startup_errors', 1);
                    ini_set('display_errors', 1);
                    self::$PE = $env;
                    break;

                case self::TESTING:
                    ini_set('error_reporting', E_ALL | E_STRICT);
                    ini_set('display_startup_errors', 1);
                    ini_set('display_errors', 1);
                    self::$PE = $env;
                    break;

                case self::PRODUCTION:
                default:
                    ini_set('error_reporting', 0);
                    ini_set('display_startup_errors', 0);
                    ini_set('display_errors', 0);
                    self::$PE = self::PRODUCTION;
                    break;
            }
        }
        //echo self::$PE;
    }

    public static function getProjectEnvironment()
    {
        if (empty(self::$PE)) {
            self::setProjectEnvironment();
        }

        return self::$PE;
    }

    /**
     * To force to get singleton instance
     */
    static private $_instance = null;

    private function __construct() {}

    private function __clone() {}

    public static function getInstance()
    {
        if (null === self::$_instance) {
            self::$_instance = new self();
        }

        return self::$_instance;
    }

    /**
     * Class Loader
     *
     */
    public static function initLoader()
    {
        if (!include_once('Kbs/Loader.php')) {
            require_once('Zend/Loader/Exception.php');
            throw new Zend_Loader_Exception('Fail to set loader !', self::ERROR_DEVELOPMENT);
        } else {
            Kbs_Loader::registerAutoload('Kbs_Loader', true);
        }
    }

    /**
     * Configrations
     * @todo config should be cache
     *
     */
    public static function initConfig($filename, $type = 'ini', $nameSuffix = '_Config', $section = null, $options = false)
    {
        if ($type != 'ini' and $type != 'xml') {
            throw new Zend_Config_Exception('Unknown type of config file !', self::ERROR_DEVELOPMENT);
        }

        try {
            $configName = $filename . $nameSuffix;

            if (false == Zend_Registry::isregistered($configName)) {

                if (null == $section) {
                    $section = self::getProjectEnvironment();
                }

                $file = 'Kbs/Config/' . $filename;

                if ('ini' === $type) {
                    $config = new Zend_Config_Ini($file . '.' . $type, $section, $options);
                } else {
                    $config = new Zend_Config_Xml($file . '.' . $type, $section, $options);
                }

                Zend_Registry::set($configName, $config);
                return $config;
            } else {
                return Zend_Registry::get($configName);
            }
        } catch (Exception $e) {
            throw new Exception($e->getMessage(), self::ERROR_DEVELOPMENT);
        }
    }

    /**
     * Controller
     *
     */
    public static function initControllerFront()
    {
        $config = self::initConfig('Controller/Front');

        if (false == Zend_Registry::isRegistered('Zend_Controller_Front')) {
            $front = Zend_Controller_Front::getInstance();

            $front->addModuleDirectory( PROJECT_ROOT . $config->moduleDirectory )
                  ->setModuleControllerDirectoryName( $config->moduleControllerDirectoryName )
                  ->setDefaultModule( $config->defaultModule )
                  ->setParam('noErrorHandler', $config->noErrorHandler)
                  ->throwExceptions((bool) $config->throwExceptions)
                  ->returnResponse((bool) $config->returnResponse);
            /*
            $router = $front->getRouter();
            $route2 = new Zend_Controller_Router_Route(
                             ':module/language/:lang',
                             array(
                                 'module'       => 'front',
                                 'controller'   => 'language',
                                 'lang'         => 'zh',
                             ),
                             array('lang' => '[a-z]+')
                         );
            
            $route = new Zend_Controller_Router_Route(
                             ':language/:module/',
                             array(
                                 'module'       => 'front',
                                 'language'     => 'zh',
                             ),
                             array('language' => '(zh)|(en)')
                         );

            $route = new Zend_Controller_Router_Route(
                ':language/:module/:controller/:action/*',
                array('controller' => 'index',
                      'action' => 'index',
                      'module' => 'front',
                      'language' => 'zh'),
                array('language' => '(zh)')
            );
            $router->addRoute('languageRoute', $route);
            $front->setRouter($router);
            */
            
            Zend_Registry::set('Zend_Controller_Front', $front);
            return $front;
        } else {
            return Zend_Registry::get('Zend_Controller_Front');
        }
    }

    /**
     * Layout
     *
     */
    public static function initLayout($moduleName)
    {
        if (false == Zend_Registry::isregistered('Zend_Layout')) {

            $config = self::initConfig('Layout');

            if (null != $config->$moduleName) {

                if (null == $config->$moduleName->layoutPath) {
                    throw new Zend_Layout_Exception('layoutPath of module "' . $moduleName . '" can not be empty !');
                }

                if (null == $config->$moduleName->layout) {
                    throw new Zend_Layout_Exception('layout filename of module "' . $moduleName . '" can not be empty !');
                }

                $layout = Zend_Layout::startMvc()->setLayoutPath(PROJECT_ROOT . $config->$moduleName->layoutPath)
                                                 ->setLayout($config->$moduleName->layout);

                Zend_Registry::set('Zend_Layout', $layout);
                return $layout;

            } else {
                throw new Zend_Layout_Exception('layout of module "' . $moduleName . '" missing !');
            }

        } else {
            return Zend_Registry::get('Zend_Layout');
        }
    }

    /**
     * View
     *
     */
    public static function initView($moduleName)
    {
        if (false == Zend_Registry::isregistered('Zend_View')) {

            $config = self::initConfig('View');

            if (null != $config->$moduleName) {

                if (null == $config->encoding) {
                    throw new Zend_View_Exception('encode setting missing !');
                }

                $viewRenderer = Zend_Controller_Action_HelperBroker::getExistingHelper('viewRenderer');
                $viewRenderer->initView(PROJECT_ROOT . $config->$moduleName->viewBasePath);
                $view = $viewRenderer->view;

                $view->addHelperPath($config->helper->path, $config->helper->prefix)
                     ->addHelperPath($config->$moduleName->helper->path, $config->$moduleName->helper->prefix)
                     ->setEncoding($config->encoding)
                     ->assign(array('charset'       =>  $config->encoding,
                                    'pathImg'       =>  $config->$moduleName->pathImg,
                                    'pathJs'        =>  $config->$moduleName->pathJs,
                                    'pathCss'       =>  $config->$moduleName->pathCss));

                /**
                 * google analytics
                 */
                if (self::getProjectEnvironment() == self::PRODUCTION) {
                    $gaCcript = 'var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");'
                              . 'document.write(unescape("%3Cscript src=\'" + gaJsHost + "google-analytics.com/ga.js\' type=\'text/javascript\'%3E%3C/script%3E"));'
                              . 'try {'
                              . '   var pageTracker = _gat._getTracker("UA-8587498-1");'
                              . '   pageTracker._trackPageview();'
                              . '} catch(err) {}';
                    $view->inlineScript()->appendScript($gaCcript);
                }

                Zend_Registry::set('Zend_View', $view);
                return $view;

            } else {
                throw new Zend_View_Exception("view setting for module $moduleName hasn't been made up yet. " 
                                            . "Please check your 'view.ini' file within your configurations.");
            }

        } else {
            return Zend_Registry::get('Zend_View');
        }
                
    }

    /**
     * Plugins
     * All functionalities and plugins for each module are here !
     *
     */
    public static function initPlugin($section = 'common')
    {
        $config = self::initConfig('Controller/Plugin');

        if (null != $config->$section) {

            $front = self::initControllerFront();

            if (null != $config->$section->className) {

                $plugins = $config->$section->className->toArray();

                foreach ($plugins as $name => $stackIndex) {

                    $plugin = $config->$section->classPrefix . $name;

                    if (class_exists($plugin) and !$front->hasPlugin($plugin)) {
                        $front->registerPlugin(new $plugin, $stackIndex);
                    } else {
                        throw new Zend_Controller_Exception("Plugin '$plugin' not exists !", self::ERROR_DEVELOPMENT);
                    }
                }
            }
        }
    }

    /**
     * Helpers
     *
     */
    /*
    public static function initHelper($section = 'common')
    {
        $config = self::initConfig('Controller/Helper');

        if (null != $config->$section and null != $config->$section->name) {

            $helpers = $config->$section->name->toArray();

            foreach ($helpers as $name => $stackIndex) {

                $helper = $config->$section->prefix . $name;

                require_once('Extension/Loader.php');
                Extension_Loader::loadClass($helper);

                if (class_exists($helper) and !Zend_Controller_Action_HelperBroker::hasHelper($name)) {

                    Zend_Controller_Action_HelperBroker::getStack()->offsetSet($stackIndex, new $helper);
                }
            }
        }
    }
    */

    /**
     * Auth Http
     *
     */
    public static function initAuthHttp(Zend_Controller_Request_Abstract $request, Zend_Controller_Response_Abstract $responce)
    {
        $config = self::initConfig('Auth/Http');

        if ($config->enable) {

            $auth = Zend_Auth::getInstance();

            //$namespace = self::initConfig('Session')->namespace->auth->http;
            //require_once('Extension/Auth/Storage/Session.php');
            //$storage = new Extension_Auth_Storage_Session($namespace);
            //$auth->setStorage($storage);

            if (!$auth->hasIdentity()) {
  
                $basicResolver = new Zend_Auth_Adapter_Http_Resolver_File();
                $basicResolver->setFile(PROJECT_ROOT . $config->resolver->basic);
                $digestResolver = new Zend_Auth_Adapter_Http_Resolver_File();
                $digestResolver->setFile( PROJECT_ROOT . $config->resolver->digest);

                $authAdapterHttp = new Zend_Auth_Adapter_Http($config->options->toArray());
                $authAdapterHttp->setRequest($request);
                $authAdapterHttp->setResponse($responce);

                $authAdapterHttp->setBasicResolver($basicResolver);
                $authAdapterHttp->setDigestResolver($digestResolver);

                //Zend_Registry::set('authAdapterHttp', $authAdapterHttp);

                $auth = Zend_Auth::getInstance();
                $result = $auth->authenticate($authAdapterHttp);

                if (!$result->isValid()) {
                    //echo md5('admin') . '<br />';
                    //echo md5('site') . '<br />';
                    //echo md5('admin') . '<br />';
                    //echo MD5('kimho:site:admin') . '<br />';
                    //echo base64_encode('kim') . '<br />';
                    //file_put_contents(PROJECT_ROOT . $config->resolver->digest, 'kim:site:'.md5('kim'));

                    echo $authAdapterHttp->getResponse();
                    echo $messages = implode('<br />', $result->getMessages());
                    exit();
                }
            }

        } else {
            return true;
        }
    }

    /**
     * Database Connection
     *
     */
    public static function initDb()
    {
        if (false == Zend_Registry::isregistered('Zend_Db')) {

            $config = self::initConfig('Db');

            //$options = array(Zend_Db::AUTO_QUOTE_IDENTIFIERS => false, PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true);

            $db = Zend_Db::factory($config->db);

            if ($db->getConnection()) {
                $db->query("SET NAMES '{$config->db->charset}'");
                Zend_Registry::set('Zend_Db', $db);
                return $db;
            } else {
                throw new Zend_Db_Exception($config->noConnectMessage);
            }

        } else {
            return Zend_Registry::get('Zend_Db');
        }
    }

    /**
     * Session
     *
     */
    public static function initSession($namespace = false, $options = array())
    {
        //$config = self::initConfig('Session');
/*
        if (!$options and (null != $config->options) and is_array($config->options->toArray())) {
            $options = $config->options->toArray();
            $options['save_path'] = PROJECT_ROOT . $config->options->save_path;
            Extension_Session::setOptions($options);
        } elseif (is_array($options)) {
            Extension_Session::setOptions($options);
        }

        if ($config->regenerate_id) {
            Extension_Session::regenerateId();
        }
*/
        Zend_Session::start();

        if (!$namespace) {
            //$session = new Zend_Session_Namespace($config->namespace->default);
            $session = new Zend_Session_Namespace();
            /*
            if ($config->default->expirationHops) {
                $session->setExpirationHops($config->default->expirationHops);                
            }
            if ($config->default->expirationSeconds) {
                $session->setExpirationSeconds($config->default->expirationSeconds);
            }
            */
        } else {
            $session = new Zend_Session_Namespace((string) $namespace);
        }

        return $session;
    }

    /**
     * Locale
     *
     */
    public static function initLocale()
    {
        if (false == Zend_Registry::isRegistered('Zend_Locale')) {

            $config = self::initConfig('Locale');

            //$namespace = self::initConfig('Session')->namespace->locale;
            $session = self::initSession('Locale');

            /*
            $cache = self::initCache('Locale');
            if ($cache instanceof Zend_Cache_Core) {
                Zend_Locale::setCache($cache);
            }
            */

            if (null != $session->locale) {
                $locale = new Zend_Locale($session->locale);
            } else {
                $locale = new Zend_Locale('auto');
            }

            Zend_Registry::set('Zend_Locale', $locale);
            return $locale;

        } else {
            return Zend_Registry::get('Zend_Locale');
        }
    }

    /**
     * Translate
     *
     */
    public static function initTranslate(Zend_Controller_Request_Abstract $request, Zend_View_Abstract $view = null)
    {
        $config = self::initConfig('Translate');

        if ($config->enable) {
            if (null == $view) {
                $view = self::initView($request->getModuleName());
            }

            $locale = self::initLocale();

            //$cacheTranslate = Kbs::initCache('Translate', $request->getModuleName());
            //if ($cacheTranslate instanceof Zend_Cache_Core) {
            //    Extension_Translate::setCache($cacheTranslate);
            //}
        
            $lang = "Kbs/Translate/Language/$locale.php";

            if (!Zend_Loader::loadFile($lang)) {
                throw new Zend_Translate_Exception($config->errMessage);
            } else {
                if (isset($config->options)) {
                    $options = $config->options->toArray();
                }
                $translator = new Zend_Translate($config->adapter, require $lang, $locale, $options);
                Zend_Registry::set('Zend_Translate', $translator);
                return $translator;
            }
        } else {
            return false;
        }
    }

    /**
     * Date
     *
     */
    /*
    public static function initDate()
    {
        if (false == Zend_Registry::isRegistered('Zend_Date')) {

            $config = self::initConfig('Date');

            $options = array(
                'format_type'   =>  $config->format_type,
                'fix_dst'       =>  (bool) $config->fix_dst,
                'extend_month'  =>  (bool) $config->extend_month,
            );

            require_once('Zend/Date.php');
            $date = Zend_Date::now();
            $date->setOptions($options);
            $date->setLocale(self::initLocale());
            $date->setTimezone($config->timezone);

            Zend_Registry::set('Zend_Date', $date);
            return $date;

        } else {

            $date = Zend_Registry::get('Zend_Date');
            $date->set(Zend_Date::now());
            return $date;
        }
    }
    */

    /**
     * Cache
     *
     */
    public static function initCache($name = 'Default', $prefix = '')
    {
        $config = self::initConfig("Cache/$name");

        if (false == Zend_Registry::isregistered($name)) {

            $backendOptions = $config->backend->options->toArray();

            if (!empty($prefix)) {
                $backendOptions['file_name_prefix'] = $prefix;
            }

            $backendOptions['cache_dir'] = PROJECT_ROOT . $config->backend->options->cache_dir;

            $customFrontendNaming = false;
            if (isset($config->frontend->customFrontendNaming)) {
                $customFrontendNaming = (bool) $config->frontend->customFrontendNaming;
            }

            $customBackendNaming = false;
            if (isset($config->backend->customBackendNaming)) {
                $customBackendNaming = (bool) $config->backend->customBackendNaming;
            }

            $autoload = false;
            if (isset($config->autoload)) {
                $autoload = (bool) $config->$name->autoload;
            }

            $cache = Zend_Cache::factory(
                $config->frontend->type, 
                $config->backend->type, 
                $config->frontend->options->toArray(), 
                $backendOptions,
                $customFrontendNaming,
                $customBackendNaming,
                $autoload
            );

            if (isset($config->cacheId)) {
                $cache->id = $config->cacheId;
            } else {
                $cache->id = $name;
            }

            if (isset($config->cacheTags)) {
                $cache->tags = explode(',', $config->cacheTags);
            } else {
                $cache->tags = array();
            }

            Zend_Registry::set($name, $cache);
            return $cache;

        } else {
            return Zend_Registry::get($name);
        }
    }

    /**
     * the memory manager
     *
     */
    /*
    public static function initMemory()
    {
        if (false == Zend_Registry::isregistered('Zend_Memory')) {
            $config = self::initConfig('Memory');

            $memoryManager = Zend_Memory::factory($config->backend->type, $config->backend->options->toArray());
            $memoryManager->setMemoryLimit($config->memoryLimit);
            $memoryManager->setMinSize($config->minSize);

            Zend_Registry::set('Zend_Memory', $memoryManager);

            return $memoryManager;
        } else {
            return Zend_Registry::get('Zend_Memory');
        }
    }
    */

    /**
     * search lucene
     *
     */
    /*
    public static function initSearchLucene($action = 'create')
    {
        $config = self::initConfig('Search/Lucene');

        if ($config->enable) {
            require_once('Zend/Search/Lucene.php');
            Zend_Search_Lucene::setResultSetLimit($config->resultSetLimit);

            if (isset($config->defaultSearchField) and !empty($config->defaultSearchField)) {
                Zend_Search_Lucene::setDefaultSearchField($config->defaultSearchField);
            }

            if (isset($config->enableUtf8Analyzer) and $config->enableUtf8Analyzer) {
                $analyzer = new Zend_Search_Lucene_Analysis_Analyzer_Common_Utf8();

                $stopWordsFilter = new Zend_Search_Lucene_Analysis_TokenFilter_StopWords();

                $stopWordsFilter->loadFromFile(PROJECT_ROOT . $config->stopwordsFile);

                $analyzer->addFilter($stopWordsFilter);

                Zend_Search_Lucene_Analysis_Analyzer::setDefault($analyzer);
            }

            Zend_Search_Lucene_Search_QueryParser::setDefaultEncoding($config->encoding);
            Zend_Search_Lucene_Search_QueryParser::dontSuppressQueryParsingExceptions();

            if ($action == 'create') {
                $luceneIndex = Zend_Search_Lucene::create(PROJECT_ROOT . $config->directory);
                $luceneIndex->encoding = $config->encoding;
            } elseif ($action == 'open') {
                $luceneIndex = Zend_Search_Lucene::open(PROJECT_ROOT . $config->directory);
                $luceneIndex->encoding = $config->encoding;
            } elseif ($action == 'delete') {
                $luceneIndex = Zend_Search_Lucene::open(PROJECT_ROOT . $config->directory);
            } else {
                throw new Zend_Search_Lucene_Exception('incorrect action in search lucene !');
            }

            Zend_Registry::set('luceneIndex', $luceneIndex);
            return $luceneIndex;
        } else {
            throw new Zend_Search_Lucene_Exception('lucene disabled !');
        }
    }
    */

    /**
     * Mail
     *
     */
    /*
    public static function initMail()
    {
        $config = self::initConfig('Mail');

        $options = array();
        if (null != $config->transport->smtp->options) {
            $options = $config->transport->smtp->options->toArray();
        }

        $transport = new Zend_Mail_Transport_Smtp($config->transport->smtp->host, $options);
        Zend_Mail::setDefaultTransport($transport);

        $mail = new Zend_Mail($config->charset);

        if (isset($config->headers->encoding)) {
            $encoding = $config->headers->encoding;
            $mail->setEncodingOfHeaders($encoding);
        }

        return $mail;
    }
    */

    /**
     * XmlRpc client
     *
     */
    /*
    public static function initXmlRpcClient()
    {
        $config = self::initConfig('XmlRpc');

        if ($config->enable) {
            if (false == Zend_Registry::isregistered('Zend_XmlRpc_Client')) {
                $client = new Zend_XmlRpc_Client($config->xmlRpcServer);
                Zend_Registry::set('Zend_XmlRpc_Client', $client);
                return $client;
            } else {
                return Zend_Registry::get('Zend_XmlRpc_Client');
            }
        } else {
            throw new Zend_XmlRpc_Client_Exception('xmlrpc is disabled !');
        }
    }
    */

    /**
     * XmlRpc server
     *
     */
    /*
    public static function initXmlRpcServer()
    {
        $config = self::initConfig('XmlRpc');

        if ($config->enable) {
            $server = new Zend_XmlRpc_Server();

            if ($config->caching) {
                if (!Zend_XmlRpc_Server_Cache::get(PROJECT_ROOT . $config->cacheFile, $server)) {

                    $server->setEncoding($config->encoding);
                    $server->setResponseClass($config->responseClass);

                    if (isset($config->classes)) {
                        foreach ($config->classes as $namespace => $class) {
                            $server->setClass($class, $namespace);
                        }
                    }

                    Zend_XmlRpc_Server_Cache::save(PROJECT_ROOT . $config->cacheFile, $server);
                }
            } else {
                $server->setEncoding($config->encoding);
                $server->setResponseClass($config->responseClass);

                if (isset($config->classes)) {
                    foreach ($config->classes as $namespace => $class) {
                        $server->setClass($class, $namespace);
                    }
                }
            }

            return $server;

        } else {
            throw new Zend_XmlRpc_Server_Exception('xmlrpc is disabled !');
        }
    }
    */

    /**
     * Rest client
     *
     */
    /*
    public static function initRestClient()
    {
        $config = self::initConfig('Rest');

        if ($config->enable) {
            if (false == Zend_Registry::isregistered('Zend_Rest_Client')) {
                $client = new Zend_Rest_Client($config->restServer);
                Zend_Registry::set('Zend_Rest_Client', $client);
                return $client;
            } else {
                return Zend_Registry::get('Zend_Rest_Client');
            }
        } else {
            throw new Zend_Rest_Client_Exception('rest is disabled !');
        }
    }
    */

    /**
     * Rest server
     *
     */
    /*
    public static function initRestServer()
    {
        $config = self::initConfig('Rest');

        if ($config->enable) {
            $server = new Zend_Rest_Server();
            $server->setEncoding($config->encoding);

            if (isset($config->classes)) {
                foreach ($config->classes as $namespace => $class) {
                    $server->setClass($class, $namespace);
                }
            }
            return $server;

        } else {
            throw new Zend_Rest_Server_Exception('rest is disabled !');
        }
    }
    */

    /**
     * Render output
     *
     */
    public static function output()
    {
        $front = self::initControllerFront();
        $response = $front->dispatch();

        if ($response->isException()) {
            
            $exceptions	= $response->getException();
            echo self::handleException($exceptions[0]);
        } else {
            echo $response;
        }

        /*
              $front = Zend_Controller_Front::getInstance();
              $router = $front->getRouter();
              var_dump($router);
        */
    }

    /**
     * Logger
     *
     */
    public static function initLog($section = '')
    {
        $config = self::initConfig('Log');

        if ($config->enable) {

            $logger = new Zend_Log();
            
            if (!empty($section)) {
                switch ($section) {
                    case 'XmlRpc':
                        $writerFile = new Zend_Log_Writer_Stream(PROJECT_ROOT . $config->XmlRpc->file->path);
                        $formatter = $config->XmlRpc->file->formatter;
                        $writerFile->setFormatter(new $formatter);
                        $logger->addWriter($writerFile);
                        break;
                    default:
                        break;
                }
            }

            //Zend_Registry::set('Zend_Log', $logger);
            return $logger;
        } else {
            throw new Zend_Log_Exception('logger is disabled !');
        }
    }

    /**
     * Handle the exceptions
     *
     */
    public static function handleException(Exception $e)
    {
        switch ($e->getCode()) {

            case self::ERROR_DEVELOPMENT: {
                if (!include_once(PROJECT_ROOT . '/error/500.html')) {
                    @header("HTTP/1.x 500 Internal Server Error");
                    @header('Status: 500 Internal Server Error');
                }

                if (self::getProjectEnvironment() != self::PRODUCTION) {
                    self::printException($e);
                } else {
                    self::logException($e);
                }

                exit;
                break;
            }

            default: {
                if (!include_once(PROJECT_ROOT . '/error/404.html')) {
                    @header('HTTP/1.x 404 Not Found');
                    @header('Status: 404 Not Found');
                }

                if (self::getProjectEnvironment() != self::PRODUCTION) {
                    self::printException($e);
                } else {
                    self::logException($e);
                }

                exit;
                break;

                /*
                $config = self::initConfig('Exception');
                $logger = self::initLog();

                if ($config->log->file->enable) {
                    
                    $errorMessage = self::buildException($e);
                    $errorMessage .= $config->log->file->trace ? ($e->getTraceAsString() . PHP_EOL) : '';

                    $writerFile = new Zend_Log_Writer_Stream(PROJECT_ROOT . $config->log->file->path);
                    $writerFile->addFilter(Zend_Log::DEBUG);
                    $formatter = $config->log->file->formatter;
                    $writerFile->setFormatter(new $formatter);
                    $logger->addWriter($writerFile);
                }

                if ($config->log->db->enable) {
                    $errorMessage = self::buildException($e);
                    $errorMessage .= $config->log->db->trace ? ($e->getTraceAsString() . PHP_EOL) : '';
                    $columnMapping = array($config->log->db->column->priority     => 'priority', 
                                           $config->log->db->column->message      => 'message',
                                           $config->log->db->column->timestamp    => 'timestamp');

                    $writerDb = new Zend_Log_Writer_Db(self::initDb(), $config->log->db->table, $columnMapping);
                    $writerDb->addFilter(Zend_Log::DEBUG);
                    
                    $date = self::initDate();
                    $resultDate = $date->toString($config->log->db->column->timestampFormat);

                    $logger->setEventItem('timestamp', $resultDate);
                    $logger->addWriter($writerDb);
                }

                if ($config->log->file->enable or $config->log->db->enable or $config->log->firebug->enable) {
                    $logger->log($errorMessage, Zend_Log::DEBUG);
                }

                $logger = null;
                */
            }
        }
    }

    /**
     * Print the exceptions
     *
     */
    public static function printException(Exception $e)
    {
        $errorMessage = self::buildException($e);
        echo '<br /><br />' . nl2br(print_r($errorMessage, true));
    }

    /**
     * Log the exception
     *
     */
    public static function logException(Exception $e)
    {
        $errorMessage = self::buildException($e);

        $errorLog = PROJECT_ROOT . '/repository/logs/error.log';

        if ($f = fopen($errorLog, 'a+')) {
            fwrite($f, $errorMessage);
            fclose($f);
        }
    }

    /**
     * Build the exception message
     *
     */
    public static function buildException(Exception $e, $trace = true)
    {
        $errorMessage = get_class($e);

        if ($e->getCode()) {
            $errorMessage .= PHP_EOL . ' (' . $e->getCode() . ') ';
        }

        $errorMessage .= PHP_EOL . $e->getMessage() . PHP_EOL;

        if ($trace) {
            $errorMessage .= $e->getTraceAsString() . PHP_EOL;
        }

        $errorMessage .= PHP_EOL . PHP_EOL;

        return $errorMessage;
    }


}
